<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      @darg-sort="sortTable"
      row-key="formCustomId"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" :icon="CirclePlus" @click="addTask">新增</el-button>
        <el-button type="primary" :icon="EditPen" @click="editSLA(scope.selectedList)">编辑</el-button>
        <el-button type="danger" :icon="Delete" plain :disabled="!scope.isSelected" @click="batchDelete(scope.selectedList)">
          批量删除
        </el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- usernameHeader -->
      <template #usernameHeader="scope">
        <el-button type="primary" @click="ElMessage.success('我是通过作用域插槽渲染的表头')">
          {{ scope.column.label }}
        </el-button>
      </template>
      <!-- createTime -->
      <template #createTime="scope">
        <el-button type="primary" link @click="ElMessage.success('我是通过作用域插槽渲染的内容')">
          {{ scope.row.createTime }}
        </el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <!-- <el-button type="primary" link :icon="EditPen" @click="editTemplateNameBtn([scope.row])">编辑模板名称</el-button> -->
        <el-button type="primary" link :icon="EditPen" @click="editSLA([scope.row])">编辑</el-button>
        <el-button type="primary" link :icon="Delete" @click="batchDelete([scope.row])">删除</el-button>
      </template>
    </ProTable>

    <el-dialog title="自定义表单" v-model="dialogTableVisible">
      <!-- <el-dialog title="选择配置项分类" v-model="dialogCiCategoryNoTableVisible" append-to-body>
		  <div :style="{ height: '500px' }">
					  <el-tree :data="cicategorySelectList" :props="defaultProps"  :default-expand-all="true" @node-click="handleNodeClickCiCategoryNo" class="custom-tree" />
				  
		  </div>
		</el-dialog> -->

      <div :style="{ height: '300px' }">
        <el-form style="width: 100%" label-width="120px" ref="ruleFormRef" :rules="rules" :model="addForm">
          <el-form-item label="表单名称 :" prop="name">
            <el-input v-model="addForm.name" />
          </el-form-item>
          <el-form-item label="模块名称 :" prop="module">
            <el-select v-model="addForm.module" class="m-2" placeholder="请选择" size="large">
              <el-option v-for="item in moduleOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="自定义类型 :" prop="eav" v-if="addForm.module == 'request'">
            <el-select v-model="addForm.eav" class="m-2" placeholder="请选择" size="large" @change="changeEav">
              <el-option v-for="item in eavOptions" :key="item.eavNo" :label="item.eavName" :value="item.eavNo" />
            </el-select>
          </el-form-item>
          <el-form-item label="配置项分类 :" prop="ciCategoryNo" v-if="addForm.module != 'request'">
            <!-- <el-input v-model="addForm.ciCategoryName" @click="dialogCiCategoryNoTableVisible==true" /> -->
            <el-tree-select
              style="width: 180px"
              v-model="addForm.ciCategoryName"
              :data="cicategorySelectList"
              :render-after-expand="false"
              :props="defaultProps"
              :default-expand-all="true"
              check-strictly
              check-on-click-node
              @node-click="handleNodeClickCiCategoryNo"
            />
          </el-form-item>
          <el-button type="primary" @click="onSubmit(ruleFormRef)"> 确认选择 </el-button>
        </el-form>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="tsx" name="useProTable">
import { ref, reactive, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useTabsStore } from "@/stores/modules/tabs";
import { User, RoleManager, OrgManager } from "@/api/interface";
import { useHandleData } from "@/hooks/useHandleData";
import { useDownload } from "@/hooks/useDownload";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/views/accessControl/roleManagement/components/ImportExcel/index.vue";
import UserDrawer from "@/views/accessControl/roleManagement/components/RoleDrawer.vue";
import { ProTableInstance, ColumnProps, HeaderRenderScope } from "@/components/ProTable/interface";
import TreeFilter2 from "@/views/accessControl/roleManagement/components/authSetting/openSetting.vue";
import { CirclePlus, Delete, EditPen, Download, Upload, View, Refresh, Avatar } from "@element-plus/icons-vue";
import { getUserDepartment } from "@/api/modules/jggl";
import { roleFind, deleteRole, tempRole, importRoleData, exportRole, setResourceByRoleIds } from "@/api/modules/accessController";
import {
  FindSlaContractManagePage,
  getUserDepartmentList,
  editSlaContractManage,
  saveSlaContractManage,
  deleteSlaContractManage,
  findSlaById,
  findByServiceDir,
  findByOrgServices,
  getConfigurationCategoryTreeAllData
} from "@/api/modules/slaProtocolManagement";

import { getCategoryTreeAllData } from "@/api/modules/dataDictionary";
import {
  findPageScheduledTask,
  saveScheduledTask,
  deleteScheduledTask,
  findScheduledTaskById,
  editScheduledTask,
  findPagerContentTemplate,
  editTemplateName,
  deleteContentTemplate,
  findPagerFormCustom,
  deleteFormCustom,
  findEavEntity,
  isFormCustomNameExisted
} from "@/api/modules/systemTools";
const route = useRoute();
const tabStore = useTabsStore();
const router = useRouter();
// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ initParamtype: 1 });
const rules = reactive<FormRules>({
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  module: [{ required: true, message: "请选择", trigger: "blur" }],
  eav: [{ required: true, message: "请选择", trigger: "blur" }],
  ciCategoryNo: [{ required: true, message: "请选择", trigger: "blur" }]
});
const defaultProps = {
  children: "children",
  label: "data"
};
const dialogCiCategoryNoTableVisible = ref(false);
const handleNodeClickCiCategoryNo = (data: any) => {
  addForm.ciCategoryName = data.data;
  addForm.ciCategoryNo = data.attr.cno;
  addForm.eav = data.attr.categoryType == undefined ? "" : data.attr.categoryType;
  dialogCiCategoryNoTableVisible.value = false;
};
const ruleFormRef = ref<FormInstance>();
const addForm = reactive({
  name: "",
  module: "request",
  eav: "",
  eavName: "",
  ciCategoryNo: "",
  ciCategoryName: ""
});
const changeEav = (val: any) => {
  eavOptions.value.forEach(function (element) {
    let newElement = JSON.parse(JSON.stringify(element));
    if (newElement.eavNo == val) {
      addForm.eavName = newElement.eavName;
    }
  });
};
const moduleOptions = [
  {
    value: "request",
    label: "请求"
  },
  {
    value: "ci",
    label: "配置项"
  }
];
const eavOptions = ref<any>([]);

// ProTable 实例
const proTable = ref<ProTableInstance>();

const dialogTableVisible = ref(false);
const dialogAddDtlVisible = ref(false);
const AddDtlName = ref("");
const TaskOption = ref("");

const onSubmit = async (formEl: FormInstance | undefined) => {
  console.log(addForm);
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      // request problem change configureItem knowledge
      // tabStore.removeTabs(route.fullPath);
      let tmp = {
        type: addForm.module,
        formCustomName: addForm.name
      };
      isFormCustomNameExisted(tmp, "formCustomQueryDTO").then(res => {
        if (res.toString() == "true") {
          if (addForm.module == "request") {
            //前往请求添加页面
            router.push(
              `/system/tools/customerForm/addRequestCustomerForm?pageNo=${Math.random().toFixed(3)}&data=` +
                JSON.stringify(addForm)
            );
            dialogTableVisible.value = false;
            return;
          } else {
            console.log("ddddddddddd");
            //前往添加配置项
            if (addForm.ciCategoryNo.toString() == "1") {
              ElMessage.error("当前配置项不可选");
              return;
            } else {
              router.push(
                `/system/tools/customerForm/addCiCustomerForm?pageNo=${Math.random().toFixed(3)}&data=` + JSON.stringify(addForm)
              );
              dialogTableVisible.value = false;
              return;
            }
          }
        } else {
          ElMessage.error("名称已存在");
        }
      });
    } else {
      ElMessage.error("请正确填写表单");
    }
  });
};
// const editTemplateNameDialogVisible = ref(false);
// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    list: data.data,
    total: data.totalSize,
    pageNum: data.page,
    pageSize: data.rows
  };
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.page = newParams.pageNum;
  newParams.rows = newParams.pageSize;
  newParams._search = false;
  newParams.sidx = "formCustomId";
  newParams.sord = "desc";
  delete newParams.pageNum;
  delete newParams.pageSize;
  return findPagerFormCustom(newParams, "formCustomQueryDTO", ["_search", "sidx", "sord", "page", "rows"]);
};

// 页面按钮权限（按钮权限既可以使用 hooks，也可以直接使用 v-auth 指令，指令适合直接绑定在按钮上，hooks 适合根据按钮权限显示不同的内容）
const { BUTTONS } = useAuthButtons();

export interface resList {
  companyName: string;
  // createTime: string;
  // description: string;
  // lastUpdateTime: string;

  taskDate: string;
  taskEndDate: string;
  timeType: string;
  title: string;

  categoryNo: number;
  companyNo: number;
  createTime: string;
  creator: string;
  dataFlag: number;
  description: string;
  formId: number;
  indexContent: string;
  isNewForm: boolean;
  isShowBorder: string;
  lastUpdateTime: string;
  lastUpdater: string;
  optimisticLock: number;
  remark: string;
  serviceDirId: number;
  templateId: number;
  templateJson: string;
  templateName: string;
  templateType: string;

  formCustomId: number;
  formCustomName: string;
  isDefault: boolean;
  type: string;
  eavName: string;
}
// 表格配置项
const columns = reactive<ColumnProps<resList>[]>([
  { type: "selection", fixed: "left", width: 70 },
  { prop: "formCustomId", label: "ID", sortable: true, width: 80 },
  { prop: "formCustomName", label: "名称", search: { el: "input" }, sortable: true },
  { prop: "isDefault", label: "名称", sortable: true, render: scope => <>{scope.row.isDefault === false ? "否" : "是"}</> },
  {
    prop: "type",
    label: "模块名称",
    sortable: true,
    width: 160,
    enum: [
      {
        genderLabel: "请求自定义表单",
        genderValue: "request"
      },
      {
        genderLabel: "配置项自定义表单",
        genderValue: "ci"
      }
    ],
    fieldNames: { label: "genderLabel", value: "genderValue" },
    search: { el: "select", props: { filterable: true } },
    render: scope => <>{scope.row.type === "request" ? "请求" : "配置项"}</>
  },
  { prop: "eavName", label: "自定义类型", search: { el: "input" }, sortable: true },
  { prop: "operation", label: "操作", fixed: "right", width: 360 }
]);

// 表格拖拽排序
const sortTable = ({ newIndex, oldIndex }: { newIndex?: number; oldIndex?: number }) => {
  ElMessage.success("修改列表排序成功");
};

// 批量删除
const batchDelete = async (id: any[]) => {
  let NameStr = "";
  let idsStr = "";
  for (let i = 0; i < id.length; i++) {
    if (idsStr == "") {
      idsStr = "?formCustomIds=" + id[i].formCustomId;
    } else {
      idsStr = idsStr + "&formCustomIds=" + id[i].formCustomId;
    }
    NameStr = NameStr + id[i].formCustomName + ",";
  }
  ElMessageBox.confirm("是否删除选中的数据：" + NameStr + " ？", "删除确认", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    center: true
  })
    .then(() => {
      deleteFormCustom(idsStr).then(res => {
        if (res == null) {
          ElMessage({
            type: "success",
            message: "删除成功"
          });
          proTable.value?.clearSelection();
          proTable.value?.getTableList();
        } else {
          ElMessage({
            type: "error",
            message: "存在关联数据无法删除，请检查"
          });
        }
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除"
      });
    });
};

const addTask = () => {
  addForm.name = "";
  addForm.eav = "";
  addForm.eavName = "";
  addForm.ciCategoryNo = "";
  addForm.ciCategoryName = "";
  dialogTableVisible.value = true;
};

const editSLA = async (params: any[]) => {
  if (params.length != 1) {
    ElMessage({
      type: "error",
      message: "只能编辑一条数据"
    });
    return;
  }
  if (params[0].type == "request") {
    //前往编辑页面
    //前往请求添加页面
    addForm["id"] = params[0].formCustomId;
    addForm.eavName = params[0].eavName;
    addForm.name = params[0].formCustomName;
    addForm.eav = params[0].eavNo;
    router.push(
      `/system/tools/customerForm/addRequestCustomerForm?pageNo=${Math.random().toFixed(3)}&data=` + JSON.stringify(addForm)
    );
    dialogTableVisible.value = false;
    return;
  } else {
    addForm["id"] = params[0].formCustomId;
    addForm.name = params[0].formCustomName;
    // addForm.eavName=params[0].eavName
    // addForm.name=params[0].formCustomName
    // addForm.eav=params[0].eavNo

    addForm.ciCategoryName = params[0].ciCategoryName;
    addForm.ciCategoryNo = params[0].ciCategoryNo;
    addForm.eav = params[0].eavNo;
    router.push(
      `/system/tools/customerForm/addCiCustomerForm?pageNo=${Math.random().toFixed(3)}&data=` + JSON.stringify(addForm)
    );
    dialogTableVisible.value = false;
    return;
  }
};

const cicategorySelectList = ref<any>([]);
onMounted(() => {
  findEavEntity().then(res => {
    (res.data as any).forEach(function (element) {
      eavOptions.value.push(element);
    });
  });
  getConfigurationCategoryTreeAllData().then(res => {
    // 使用traverseTree遍历树
    traverseTree(res as any, node => {
      if (node.attr.cname == "配置项分类") {
        node["disable"] = true;
      }
      node["label"] = node.attr.cno;
      node["value"] = node.attr.cname;
    });
    cicategorySelectList.value = [res as any];
  });
});

interface TreeNode {
  value: any;
  children?: TreeNode[];
  id: string;
  name: string;
  attr: any;
  lable: any;
  data: any;
}

function traverseTree(node: TreeNode, callback: (node: TreeNode) => void) {
  callback(node);
  if (node.children) {
    node.children.forEach(child => traverseTree(child, callback));
  }
}
</script>

<style scoped lang="scss">
.no-wrap {
  white-space: nowrap;
}
</style>
